<?php

require_once('config/maptrick.conf.php');
require_once(SITE_ROOT . 'lib/SmartyMaptrick.class.php');
require_once(SITE_ROOT . 'class/logic/Registration.class.php');
require_once(SITE_ROOT . 'class/logic/LogicFedImport.class.php');
require_once(SITE_ROOT . 'class/logic/LogicHoC.class.php');
require_once(SITE_ROOT . 'class/bean/Team.class.php');
require_once(SITE_ROOT . 'config/session.php');

$logic = new LogicFedImport();
$smarty = new SmartyMaptrick();

if (count($_POST) > 0 && ($_POST["rnd"] != $_SESSION["rnd_maptrick"] || $_POST["rnd"] == "" || !isset($_POST["rnd"]))) {
	$_SESSION = array();
	$_POST = array();
}

if ($_POST['select_alliances'] == 0) {
	$display_input = true;
	$allianceID = $_POST['input_alliance'];
}
else {
	$display_input = false;
	$allianceID = $_POST['select_alliances'];
}

if (!preg_match("/^[0-9]{1,7}$/", $allianceID)) unset($allianceID);

if (preg_match("/^[A-Za-z_-]{1,32}$/", $_POST['hidden'])) $hidden = $_POST['hidden'];

if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier']) && count($_POST) == 0) {
	try {
		$register = new Registration();
		$register->connect($_GET['oauth_token'], $_GET['oauth_verifier']);
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}

if ($hidden == 'login') {
	try {
		$register = new Registration();
		$callback = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
		$url = $register->login($callback);
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}
else if ($hidden == 'logout') {
	try {
		$register = new Registration();
		$register->logout();
	}
	catch (Exception $e) {
		$smarty->assign('message', $e->getMessage());
	}
}
else if ($hidden == 'fetch') {
	try {
		if (preg_match("/^[0-9]{1,7}$/", $allianceID)) {
			$alliance = $logic->fetchAlliance($allianceID);
		}
		else $smarty->assign('error', "The AllianceID isn't valid! It may only contain numbers.");
	}
	catch (Exception $e) {
		$errorCode = substr($e->getMessage(), strpos($e->getMessage(), "(") + 1, strpos($e->getMessage(), ")") - strpos($e->getMessage(), "(") - 1);
		switch ($errorCode) {
			case 0: {
				unset($_SESSION['login']);
				unset($_SESSION['login_team']);
				unset($_SESSION['HT']);
				$smarty->assign('message', 'Timeout!');
				break;
			}
			case 99: {
				$smarty->assign('error', "You aren't a member of this federation and must not import/update it!");
				break;
			}
			default: $smarty->assign('error', "An error has occured! Please try again later.");
		}
	}
}

if ($hidden == 'login') {
	header('Location: '. $url);
}
else {
	$smarty->assign('action', $_SERVER['PHP_SELF']);
	$smarty->assign('loggedIn', $_SESSION['login']);

	// assign the important attributes for the header
	$smarty->assign('title', 'Maptrick');
	$smarty->assign('hoc_active', 'active');

	$_SESSION["rnd_maptrick"] = hash_hmac("sha256", rand(1000000000, 9999999999), SCRIPT_PWD);
	$smarty->assign("rnd_maptrick", $_SESSION["rnd_maptrick"]);
	
	if ($_SESSION['login'] && isset($_SESSION['login_team'])) {
		$login_team = $_SESSION['login_team'];
		$smarty->assign('login_user', $login_team->getUserName());
		$smarty->assign('login_team', $login_team->getName());
		$smarty->assign('login_teamID', $login_team->getTeamID());
		if ($login_team->getLeague() != null) {
			$smarty->assign('login_leagueID', $login_team->getLeague()->getLeagueID());
			$smarty->assign('login_league', $login_team->getLeague()->getName());
		}
	}

	$smarty->assign('introduction', "<p>You can import a Hattrick federation here if you are a member of that federation. You have to be logged in to do anything here. To import a federation choose \"Enter AllianceID manually...\" and enter the ID of your federation in the textfield which appears then. To update a already imported federation just choose it from the dropdown box and press \"Fetch\" afterward. If everything was successfull a link to the Hall of Cool is presented to you where you can update all the members of the federation then.</p><p>Please update your federation once a month. One month after the last update the federation will be removed automatically. You'll have to reimport it here again then.</p>");

	$smarty->assign('selected_alliance', $allianceID);
	$smarty->assign('alliances', LogicHoC::getInstance()->getAlliances());

	if ($alliance != null) {
		$display_input = false;

		$smarty->assign("federation", $alliance);
		$smarty->assign("newMembers", $logic->getNewMembers());
		$smarty->assign("membersLeft", $logic->getMembersLeft());

		$smarty->assign('info', "The federation \"" . $alliance->getName() . "\" (" . $alliance->getAllianceID() . ") was imported/updated successfully. It currently has " . $alliance->getNumberMembers() . " members. You can take a look at the federation in the Hall of Cool by clicking <a href=\"hallofcool.php?alliance=" . $alliance->getAllianceID() . "\">here</a>.");
	}

	$smarty->assign('display_input', $display_input);

	$smarty->display('header.tpl');
	$smarty->display('fedimport.tpl');
	$smarty->display('footer.tpl');
}

?>